package org.example.camundaapp.controller;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.example.camundaapp.service.CamundaEngineService;
import org.example.camundaapp.service.ProcessService;
import org.example.camundaapp.utils.BpmnToImageConverter;
import org.example.camundaapp.utils.ProcessDiagramUtil;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * @className: ProcessDiagramController
 * @author: ZHRJ
 * @date: 2025-06-30 16:19
 * @Version: 1.0
 * @description:
 */
@RestController
@RequestMapping("/api/diagram")
@Slf4j
public class ProcessDiagramController {

    @Resource
    private HistoryService historyService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private CamundaEngineService camundaEngineService;


    /**
     * 获取当前活动的流程图
     * 存在待解决问题：
     * 1、有些流程线没有高亮显示（红色）；
     * 2、审批过的节点，被驳回后，从原节点开始，之前走过的节点依然高亮显示（红色）；
     * 3、只有红色，当前所在的节点没有其他颜色渲染；
     * @param processInstanceId
     * @return
     */
    @GetMapping(value = "/current/png/{processInstanceId}", produces = "image/png")
    public ResponseEntity<byte[]> getProcessDiagramCurrent(@PathVariable String processInstanceId) throws Exception {
        byte[] data = ProcessDiagramUtil.generateHighlightedSvg(
                historyService,
                runtimeService,
                repositoryService,
                processInstanceId
        );
        return ResponseEntity.ok(data);
    }

    /**
     * 通过部署 ID 获取流程图
     * @param deploymentId 部署 ID
     * @return PNG 格式的流程图
     * @throws  转换过程中可能出现的异常
     */
    @GetMapping(value = "/diagramByDeploymentId/{deploymentId}", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<byte[]> getDiagramByDeploymentId(@PathVariable String deploymentId) throws Exception {
        // 根据部署 ID 获取部署对象
        Deployment deployment = repositoryService.createDeploymentQuery()
                .deploymentId(deploymentId)
                .singleResult();

        if (deployment == null) {
            log.error("未找到部署 ID 对应的部署: {}", deploymentId);
            return ResponseEntity.notFound().build();
        }

        // 获取该部署下的第一个流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();

        if (processDefinition == null) {
            log.error("未找到部署 ID 对应的流程定义: {}", deploymentId);
            return ResponseEntity.notFound().build();
        }

        // 获取 BPMN XML 输入流
        InputStream bpmnInputStream = repositoryService.getResourceAsStream(
                processDefinition.getDeploymentId(),
                processDefinition.getResourceName()
        );

        // 将 BPMN XML 转换为 PNG 图片
        byte[] pngBytes = BpmnToImageConverter.convertBpmnInputStreamToPngBytes(bpmnInputStream);

        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(pngBytes);
    }

    /**
     *  获取流程图
     * @param processInstanceId 流程实例id
     * @return PNG流程图
     */
    @GetMapping(value = "/processDiagramPng/{processInstanceId}", produces = "image/svg+xml")
    public ResponseEntity<byte[]> getProcessDiagramPng(@PathVariable String processInstanceId) {
        byte[] diagram = camundaEngineService.getProcessDiagram(processInstanceId);
        return ResponseEntity.ok().contentType(MediaType.valueOf("image/svg+xml")).body(diagram);
    }

}
